import backtrader as bt


class Sma(bt.SignalStrategy):
    def __init__(self, param):
        sma1 = bt.ind.SMA(period=param['period'])
        self.crossover = bt.ind.CrossOver(self.data.close, sma1)
        # self.signal_add(bt.SIGNAL_LONGSHORT, self.crossover)
        # self.signal_add(bt.SIGNAL_LONG, self.crossover)
        # 打印self.crossover的值
        # print(self.crossover)

    @staticmethod
    def getParamList():
        return [
            {'period': 5},
            {'period': 10},
            {'period': 20},
            {'period': 40},
            {'period': 60},
            {'period': 80},
        ]

    def next(self):
        date = self.datas[0].datetime.date(0)
        co = self.crossover[0]
        if co != 0:
            # 打印时间,信号值,价格,当前市值
            print(date, co, round(self.data.close[0], 1), int(self.broker.getvalue()), int(self.broker.getcash()))
        # if not self.position:  # 不在场内，则可以买入
        if self.crossover > 0:  # 如果金叉
            self.buy()  # 买入
        elif self.crossover < 0:  # 在场内，且死叉
            self.close()  # 卖出

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            self.log('ORDER ACCEPTED/SUBMITTED', dt=order.created.dt)
            self.order = order
            return

        if order.status in [order.Expired]:
            self.log('BUY EXPIRED')

        elif order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

        # Sentinel to None: new orders allowed
        self.order = None

    # 最终
    def stop(self):
        print('最终市值:', int(self.broker.getvalue()))
